package com.qulai.amazon_us.service.basic.impl;

import com.qulai.amazon_us.domain.basic.dashboard.ProductChangeDTO;
import com.qulai.amazon_us.domain.basic.dashboard.RemainUploadDTO;
import com.qulai.amazon_us.domain.basic.dashboard.ShopStockStatsDTO;
import com.qulai.amazon_us.mapper.basic.DashboardMapper;
import com.qulai.amazon_us.service.basic.IDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class DashboardServiceImpl implements IDashboardService {

    @Autowired
    private DashboardMapper dashboardMapper;


    public List<ProductChangeDTO> getProductAddChange(String timeType, String startTimeStr, String endTimeStr, String className, String platform) {

        LocalDateTime startTime = parseStartTime(timeType, startTimeStr);
        LocalDateTime endTime = parseEndTime(timeType, endTimeStr);

        // 查询原始数据
        List<ProductChangeDTO> rawData = dashboardMapper.getProductAddChange(
                startTime, endTime, className, platform
        );
        // 按时间维度分组统计
        return groupDataByTime(rawData, timeType);
    }


    public List<RemainUploadDTO> getRemainUpload(String platform, String brand) {
        // 1. 并行查询总数量和已使用数量
        List<RemainUploadDTO> totals = dashboardMapper.getProductTotalByClassName(platform);
        List<RemainUploadDTO> usedList = dashboardMapper.getProductUsedByClass(platform, brand);

        // 2. 转换为 Map 提高查询效率
        Map<String, Integer> totalMap = totals.stream()
                .collect(Collectors.toMap(RemainUploadDTO::getClassName, RemainUploadDTO::getTotal));
        Map<String, Integer> usedMap = usedList.stream()
                .collect(Collectors.toMap(RemainUploadDTO::getClassName, RemainUploadDTO::getUsed));

        // 3. 合并结果
        return totalMap.entrySet().stream()
                .map(entry -> {
                    String className = entry.getKey();
                    int total = entry.getValue();
                    int used = usedMap.getOrDefault(className, 0);
                    return new RemainUploadDTO(className, total - used);
                })
                .sorted(Comparator.comparing(RemainUploadDTO::getRemainCount).reversed())
                .collect(Collectors.toList());
    }

    @Override
    public List<ShopStockStatsDTO> getShopStockStats(String platform, String timeType, String startTimeStr, String endTimeStr) {
        LocalDateTime startTime = null;
        LocalDateTime endTime = null;
        if (Objects.nonNull(startTimeStr) && Objects.nonNull(endTimeStr)) {
            startTime = parseStartTime(timeType, startTimeStr);
            endTime = parseEndTime(timeType, endTimeStr);
        }
        List<ShopStockStatsDTO> shopStockStats = dashboardMapper.selectShopStockStats().stream()
                .filter(item -> item.getTotal() > 0) // 过滤无效数据
                .collect(Collectors.toList());

        // 计算合计
        ShopStockStatsDTO total = new ShopStockStatsDTO();
        total.setShop("Total");
        total.setTotal(shopStockStats.stream().mapToInt(ShopStockStatsDTO::getTotal).sum());
        total.setLowStock(shopStockStats.stream().mapToInt(ShopStockStatsDTO::getLowStock).sum());

        // 添加合计到列表
        shopStockStats.add(total);

        // 根据getTotal降序排序
        shopStockStats.sort(Comparator.comparingInt(ShopStockStatsDTO::getTotal).reversed());

        return shopStockStats;
    }


    // 按时间维度分组统计
    private List<ProductChangeDTO> groupDataByTime(
            List<ProductChangeDTO> rawData,
            String timeType
    ) {
        Map<String, Integer> timeCountMap = new LinkedHashMap<>();

        for (ProductChangeDTO data : rawData) {
            String timeKey = formatTime(data.getCreateTime(), timeType);
            timeCountMap.put(timeKey, timeCountMap.getOrDefault(timeKey, 0) + 1);
        }

        // 转换为 DTO 列表并按时间排序
        return timeCountMap.entrySet().stream()
                .map(entry -> new ProductChangeDTO(entry.getKey(), entry.getValue()))
                .sorted(Comparator.comparing(ProductChangeDTO::getTime))
                .collect(Collectors.toList());
    }

    // 格式化时间维度
    private String formatTime(LocalDateTime dateTime, String timeType) {
        return timeType.equals("day")
                ? dateTime.toLocalDate().toString()
                : dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM"));
    }

    // 解析起始时间
    private LocalDateTime parseStartTime(String timeType, String timeStr) {
        if (timeType.equals("day")) {
            LocalDate date = LocalDate.parse(timeStr, DateTimeFormatter.ISO_DATE);
            return date.atStartOfDay();
        } else {
            YearMonth yearMonth = YearMonth.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM"));
            return yearMonth.atDay(1).atStartOfDay();
        }
    }

    // 解析结束时间
    private LocalDateTime parseEndTime(String timeType, String timeStr) {
        if (timeType.equals("day")) {
            LocalDate date = LocalDate.parse(timeStr, DateTimeFormatter.ISO_DATE);
            return date.atTime(23, 59, 59);
        } else {
            YearMonth yearMonth = YearMonth.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM"));
            return yearMonth.atEndOfMonth().atTime(23, 59, 59);
        }
    }
}
